// import moment from "moment";
// import _ from "../../static/js/underscore-min.js";
import _ from "underscore";
import moment from "moment";

import Vue from 'vue';

import api from '../api';
import {
  mapState,
  mapActions
} from 'vuex'
// doTaskEdit,tagAdd,tagDel,tagSet,taskGet,taskAdd,taskSet,taskDel

export const taskAndTag = {
  data() {
    return {
      initSystemTags: ["created", "started", "need", "done", "toggle", "cancelled", "due", "used", "usedCalc", "to", "repeat", "critical", "high", "low", "minor"]
    }

  },
  methods: {
    doTaskMend(item1) {
      if (item1.state != "done") return console.log("任务完成后才能重新开启任务修改")
      let tag = this.tagDic[item1.id + "_done"];
      api.taskMend({ id: item1.id, tagid: tag.id }).then(data => {
        if (data.errno != 0) return console.log(data.errmsg, 'warning');
        // 删除done标签改成toggle,修改task.state=started, task.tags["toggle"]=moment().format("YYYY-MM-DD HH:mm:ss")
        delete this.tagDic[item1.id + "_done"];
        this.tagDic[item1.id + "_toggle"] = tag;
        let value = moment().format("YYYY-MM-DD HH:mm:ss");
        Vue.set(item1.tags, "toggle", value);
        item1.state = "started";
      })
    },
    doTaskEdit(item1, key, value) { // 只修改 done cancelled toggle   ''
      console.log("doTaskEdit in");
      if (item1.state == key && value == null) { //如果状态相同则不修改.
        return;
      }
      let item = item1; //this.taskDic[item1.id];
      let realKey = key;
      if (item.state == "toggle" && key == "toggle") { //第二次暂停,是继续状态.
        realKey = "started";
      }
      let data = { id: item.id, state: realKey };
      let tag;
      item.tags = item.tags || {}; // 如果为空着添加字段;
      if (key == "" || key == "done" || key == "cancelled") { //删除对应冲突的tag 
        if (key == "cancelled" && item.tags["done"] != undefined) {
          tag = this.tagDic[item.id + "_done"]; //item.tags["done"];
        } else if (key == "done" && item.tags["cancelled"] != undefined) {
          tag = this.tagDic[item.id + "_cancelled"]; // item.tags["cancelled"];
        }
        if (tag) {
          this.tagDel(tag, false, item);
        }
      }
      if (key == "") { //如果改为未完成. 就删除完成和取消的标签状态.
        if (item.tags["done"] != undefined) {
          tag = this.tagDic[item.id + "_done"];
          this.tagDel(tag, true, item);
        }
        if (item.tags["cancelled"] != undefined) {
          tag = this.tagDic[item.id + "_cancelled"]; // 
          this.tagDel(tag, true, item);
        }
        if (item.tags["started"] != undefined) {
          tag = this.tagDic[item.id + "_started"]; // 
          this.tagDel(tag, true, item);
        }
        if (item.tags["used"] != undefined) {
          tag = this.tagDic[item.id + "_used"]; // 
          this.tagDel(tag, true, item);
        }
      }
      let promise, tempProm;
      // if (["due", "need"].indexOf(key) > -1 && ["started", "toggle"].indexOf(item.state) > -1) {
      //如果已经开始执行任务, 修改due或need不修改任务状态. 前期设置任务状态可以更好的看到任务进度.
      if (["done", "cancelled", "toggle", "started", ""].indexOf(key) > -1) {
        console.log(data)
        promise = this.taskSet(data, item);
      }

      if ((key == "done" || realKey == "toggle") && item.tags["started"]) { //计算并添加 used标签.
        let last = item.tags["toggle"] || item.tags["started"];
        let past = moment().diff(last).valueOf();
        let resTime = '';
        if (item.tags["used"]) {
          resTime = this.timeAddCalc(item.tags["used"], this.formatTime2(past));
          console.log("calc:", resTime, item.tags["used"], this.formatTime2(past));
        } else {
          resTime = this.formatTime2(past);
        }
        tempProm = this.doTagSet(item, "used", resTime);
        promise = promise || tempProm;
      }
      if (key != "") {
        tempProm = this.doTagSet(item, key, value);
        promise = promise || tempProm;
        // 如果开始时, due没有赋值或者没有具体到时刻,就直接自动赋值当前开始时间.
        if (key == "started" && (item.tags["due"] == undefined || item.tags["due"].length < 11)) {
          this.doTagSet(item, "due", value);
        }
      }

      //项目列表拖动 删除标签再添加标签
      var _this = this;
      if (this.projectPart && this.projectPart.some(function(proTag) { return proTag == key; })) {
        if (this.projectPart) {
          this.projectPart.forEach(function(proTag) {
            if (item.tags[proTag] != undefined) {
              _this.tagDel({
                id: _this.tagDic[item.id + '_' + proTag].id,
                key: proTag
              }, true, item);
            }
          })
        }
      }
      console.log("key", key);
      return promise;
    },
    timeAddCalc(time1, time2) { //只有01:10 时分计算,不包含秒.
      let res = 0;

      let t1 = moment.duration(time1).valueOf();
      let t2 = moment.duration(time2).valueOf();
      return this.formatTime2(t1 + t2);
    },
    formatTime(time) {
      time = Math.floor(time / 1000); //毫秒
      // 计算
      var h = 0,
        i = 0,
        s = parseInt(time);
      if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
        if (i > 60) {
          h = parseInt(i / 60);
          i = parseInt(i % 60);
        }
      }
      // 补零
      var zero = function(v) {
        return (v >> 0) < 10 ? "0" + v : v;
      };
      if (h > 0) {
        return [h, zero(i)].join(":");
      } else {
        return i + "m";
      }
    },
    formatTime2(time) {
      time = Math.floor(time / 1000); //毫秒
      // 计算
      var h = 0,
        i = 0,
        s = parseInt(time);
      if (s > 60) {
        i = parseInt(s / 60);
        s = parseInt(s % 60);
        //      if (s > 0) { //时间秒向上取整,添加到'分'.
        //        i++;
        //        s = 0;
        //      }
        if (i > 60) {
          h = parseInt(i / 60);
          i = parseInt(i % 60);
        }
      }
      //    else if (s > 0) {
      //      i = 1;
      //      s = 0;
      //    }
      // 补零
      var zero = function(v) {
        return (v >> 0) < 10 ? "0" + v : v;
      };
      // if (h > 0) {
      return [zero(h), zero(i), zero(s)].join(":");
      // } else {
      //   return [zero(i), zero(s)].join(":");
      // }
    },
    usertask(id) {
      let _this = this;
      return api.usertask({ id: id }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        try {
          if (!this.wsLogin && this.sid) this.$socket.emit('wsLogin', JSON.stringify({ uid: id, token: api.token }));
          console.info("socket登录", this.wsLogin, this.sid);
        } catch (e) {
          console.error("socket登录错误");
        }
        data = data.data;
        data.type = "z39/usertask";
        var tagDic = {};
        var tasks = data.none.concat(data.today);
        this.$store.commit({ type: "socketOpen", value: true });
        _this.$store.commit(data);
        _this.$store.commit({ type: "z39/taskToDB", tasks: tasks, act: "add" });
        _this.tagitemsGet();
        return Promise.resolve(data);
      })
    },
    doTagSet(item, key, value, show, alertType) {
      let hide = !show;
      value = value || "";
      item.tags = item.tags || {}; // 如果为空着添加字段;
      let sdata;
      if (item.tags[key] == undefined || key == "toggle") { //添加
        sdata = { taskid: item.id, key: key, value: value };
        this.tagAdd(sdata, hide, item, alertType);
      } else { //修改
        var tagId = this.tagDic[item.id + '_' + key].id;
        sdata = { id: tagId, key: key, value: value };
        if (key == "used") sdata.key = "used"; //减少后端计算一级任务时长时查询数据库.
        this.tagSet(sdata, hide, item, alertType);
      }
      if (key == 'due') {
        this.$store.commit({ type: "z39/daysDic", day: value });
      }
      //    console.log("item.tags", item, item.tags, sdata);
    },
    tagAdd(sdata, hide, item) {
      let _this = this;
      let task = item; // this.taskDic[item.id];   在z39/tagSet也会从字段中获取.
      sdata.value = sdata.value || "";
      sdata.taskid = item.id;
      return api.tagAdd(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        sdata.id = data;
        this.$store.commit({ type: "z39/tagSet", task: task, sdata: sdata });
        if (!hide) {
          this.showNotice("设置成功", 'success');
        }
        return Promise.resolve(data);
      })
    },
    tagsAdd(tagKeyArr, hide, item) { // tagKeyArr=["need","due",...]
      var len = tagKeyArr.length;
      for (var i = 0; i <= len - 1; i++) {
        var key = tagKeyArr[i];
        this.tagAdd({ taskid: item.id, key: key }, hide, item);
      }
    },
    tagsDel(tagKeyArr, hide, item) { // tagKeyArr=["need","due",...]
      var len = tagKeyArr.length;
      var tag;
      for (var i = 0; i <= len - 1; i++) {
        var key = tagKeyArr[i];
        tag = this.tagDic[item.id + "_" + key];
        this.tagDel(tag, hide, item);
      }
    },
    tagDel(tag, hide, item) {
      let _this = this;
      return api.tagDel({ id: tag.id, key: tag.key }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        Vue.delete(item.tags, tag.key);
        if (!hide) {
          this.showNotice("删除成功", 'success');
        }
        return Promise.resolve(data);
      })
    },
    tagSet(sdata, hide, item, alertType) {
      let _this = this;
      let task = item; //this.taskDic[item.id];
      sdata.value = sdata.value || "";
      return api.tagSet(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        this.$store.commit({ type: "z39/tagSet", task: task, sdata: sdata });
        if (!hide) {
          this.showNotice("设置成功", 'success');
          if (alertType == 'notify') {
            _this.$notify({
              title: '成功',
              message: '设置成功',
              type: 'success'
            });
          }
        }
        return Promise.resolve(data);
      })
    },
    tasksAdd(sdata) { 
      return api.tasksAdd(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        this.showNotice("添加成功,需要刷新查看", 'success');
        return Promise.resolve(data);
      })
    },
    taskGet(id) { //接口未使用. 在任务详情中会需要.
      let _this = this;
      return api.taskGet({ id: id }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        let tasks = data.tasks || [];
        // delete data.tasks ;
        let temp = [data].concat(tasks);
        _this.$store.commit({ type: "z39/taskToDB", tasks: temp, act: "add" });
        _this.$store.commit({ type: "z39/taskCurr", task: data });
        return Promise.resolve(data);
      })
    },
    taskAdd(sdata, tags, notAdd) { //notAdd 不自动添加uid
      sdata.title = sdata.title.trim();
      if (_.isEmpty(sdata.title)) {
        this.showNotice("请输入标题", 'warning');
        return Promise.reject("title null");
      }
      let _this = this;
      let tempTask;
      if (tags != undefined && tags != null) {
        sdata.tags = tags;
      }
      return api.taskAdd(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        data.state = data.state || "";
        data.desc = data.desc || "";
        if (data.uid_auto != undefined) {
          delete data.uid_auto;
        }
        if (data.token != undefined) {
          delete data.token;
        }
        _this.$store.commit({ type: "z39/taskToDB", tasks: [data], act: "add" });
        // _this.resetInput();
        this.showNotice("添加成功", 'success');
        return Promise.resolve(data);
      })
    },
    taskSet(sdata, task) {
      // console.log("taskset in");
      let _this = this;
      return api.taskSet(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        if (sdata.tags) {
          this.$store.commit(_.extend({ type: "z39/taskSet" }, sdata, { task: task }));
        }
        if (task != null) {
          if (sdata.title && sdata.title != task.title) task.title = sdata.title;
          if (sdata.pid && sdata.pid != task.pid) task.pid = sdata.pid;
          if (sdata.desc && sdata.desc != task.desc) task.desc = sdata.desc;
          if (sdata.state != undefined && sdata.state != task.state) task.state = sdata.state;
          if (sdata.uid && sdata.uid != task.uid) task.uid = sdata.uid;
          sdata.state == 'done' ? (task.finished = true) : (task.finished = false)
        }
        this.showNotice("修改成功", 'success');
        return Promise.resolve(data);
      })
    },
    taskDel(id) {
      let _this = this;
      return api.taskDel({ id: id }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/taskToDB", tasks: [{ id: id }], act: "del" });
        this.showNotice("删除成功", 'success');
        return Promise.resolve(data);
      })
    },
    tasksGet(sdata) {
      let _this = this;
      return api.tasksGet(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        let tasks = data.tasks.concat(data.likes || []);
        _this.$store.commit({ type: "z39/taskToDB", tasks: tasks, act: "add" });
        return Promise.resolve(data);
      })
    },
    tagitemsGet() {
      let _this = this;
      return api.tagitemsGet({}).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/tagitems", tagitems: data });
        return Promise.resolve(data);
      })
    },
    projectsGet(sdata) {
      let _this = this;
      return api.projectGet(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        return Promise.resolve(data);
      })
    },
    projectGet(id) {
      let _this = this;
      return api.projectGet({ id: id }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/taskToDB", tasks: data.tasks, act: "add", override: true });
        return Promise.resolve(data);
      });
    },
    showNotice(msg, type, isPc) {
      isPc = true;
      type = type || "success";
      if (!isPc) { //手机版
        this.$vux.toast.show({ text: msg, type: type })
      } else {
        this.$message({ message: msg, type: type });
      }
    },
    projectAdd(sdata) {
      let _this = this;
      return api.projectAdd(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        sdata.id = data;
        sdata.gid = data;
        _this.$store.commit({ type: "z39/projectAdd", project: sdata });
        this.showNotice("添加成功", 'success');
        return Promise.resolve(data);
      })
    },
    projectSet(sdata) {
      let _this = this;
      return api.projectSet(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/projectSet", project: sdata });
        this.showNotice("修改成功", 'success');
        return Promise.resolve(data);
      })
    },
    projectDel(id) {
      let _this = this;
      return api.projectDel({ id: id }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        _this.$store.commit({ type: "z39/projectDel", id: id });
        this.showNotice("删除成功", 'success');
        return Promise.resolve(data);
      })
    },
    repeatAdd(sdata) {
      let _this = this;
      return api.repeatAdd(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        sdata.id = data;
        this.showNotice("添加成功", 'success');
        return Promise.resolve(data);
      })
    },
    repeatSet(sdata) {
      return api.repeatSet(sdata).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        this.showNotice("设置成功", 'success');
        return Promise.resolve(data);
      })
    },
    repeatDel(id) {
      let _this = this;
      return api.repeatDel({ id: id }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        this.showNotice("取消重复", 'success');
        return Promise.resolve(data);
      })
    },
    getTasksList: function(params) {
      return api.sortdayGet(params).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning', true);
          return Promise.reject(data.errmsg);
        }
        var taskList = data.data.tasks;
        this.$store.commit({
          type: "z39/taskToDB",
          tasks: taskList,
          act: "add"
        });
        return Promise.resolve(data.data);
      })
    },
    //标签模板添加
    addTagTmp: function(tagItem) {
      //评估重复调用这个接口，负责人to先不做，其他和开发用弹窗的方法
      if (this.addCardItemLoading) {
        return Promise.reject("loading");
      };
      if (!this.addCardItemTitle) {
        this.showNotice('请输入标题', 'warning', true);
        return Promise.reject("miss title");
      }

      var titleText = this.addCardItemTitle.trim();
      //如果添加的标签是need,要做时间格式化 1:30
      if (tagItem.key == 'need') {
        var reg = /^\d$/ig;
        if (!reg.test(titleText)) {
          this.showNotice('格式输入有误，必须是纯数字', 'warning', true);
          return Promise.reject("miss title");
        } else if (titleText > 1440) {
          this.showNotice('输入的值需小于1440', 'warning', true);
          return Promise.reject("miss title");
        } else {
          titleText = parseInt(titleText / 60) + ':' + (titleText % 60)
        }
      }
      this.addCardItemLoading = true;
      var params = {
        id: tagItem.id,
        pid: null,
        count: null,
        type: 1,
        name: tagItem.name,
        key: tagItem.key,
        tmp: tagItem.key + '=' + titleText + ',' + tagItem.tmp
        //      tmp: tagItem.key//+',' + tagItem.tmp
      }
      if (tagItem.init == 1) {
        return api.tagTmpAdd(params).then(data => {
          this.addCardItemLoading = false;
          if (data.errno != 0) {
            this.showNotice(data.errmsg, 'warning', true);
            return Promise.reject(data.errmsg);
          }
          this.addCardItemTitle = '';
          this.showNotice('保存成功', 'success', true);
          this.$store.commit({ type: "z39/updateTagTmps", id: data.data, tmp: params.tmp, key: tagItem.key });
          return Promise.resolve(data.data);
        })
      } else {
        return api.tagTmpPut(params).then(data => {
          this.addCardItemLoading = false;
          if (data.errno != 0) {
            this.showNotice(data.errmsg, 'warning', true);
            return Promise.reject(data.errmsg);
          }
          this.addCardItemTitle = ''
          this.showNotice('保存成功', 'success', true);
          this.$store.commit({ type: "z39/updateTagTmps", id: params.id, tmp: params.tmp, key: tagItem.key });
          return Promise.resolve(data.data);
        })
      }
    },
    sortdayGet(day) {
      return api.sortdayGet({ day }).then(data => {
        if (data.errno != 0) {
          this.showNotice(data.errmsg, 'warning');
          return Promise.reject(data.errmsg);
        }
        data = data.data;
        // this.sortStr = data.sorts ;
        this.$store.commit({ type: "z39/taskToDB", tasks: data.tasks, act: "add" });
        console.log(data);
        return Promise.resolve(data);
      })
    },
  }

}
